document.addEventListener('DOMContentLoaded', function() {
    // 初始化图表
    const sentimentChart = echarts.init(document.getElementById('sentimentChart'));
    const volumeChart = echarts.init(document.getElementById('volumeChart'));
    const mapChart = echarts.init(document.getElementById('mapChart'));
    const sourceChart = echarts.init(document.getElementById('sourceChart'));
    
    // 获取时间范围
    const timeRangeSelect = document.getElementById('timeRange');
    const refreshBtn = document.getElementById('refreshBtn');
    
    // 加载初始数据
    loadDashboardData(timeRangeSelect.value);
    
    // 刷新按钮点击事件
    refreshBtn.addEventListener('click', function() {
        loadDashboardData(timeRangeSelect.value);
    });
    
    // 窗口大小变化时重新调整图表大小
    window.addEventListener('resize', function() {
        sentimentChart.resize();
        volumeChart.resize();
        mapChart.resize();
        sourceChart.resize();
    });
    
    // 加载仪表盘数据
    function loadDashboardData(days) {
        // 显示加载状态
        showLoading();
        
        // 获取统计数据
        fetch(`/api/statistics?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 更新数据概览
                updateOverview(data);
                
                // 更新情感分布图表
                updateSentimentChart(sentimentChart, data);
                
                // 隐藏加载状态
                hideLoading();
            })
            .catch(error => {
                console.error('获取统计数据失败:', error);
                hideLoading();
            });
        
        // 获取声量趋势数据
        fetch(`/api/volume_trend?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 更新声量趋势图表
                updateVolumeChart(volumeChart, data);
            })
            .catch(error => {
                console.error('获取声量趋势数据失败:', error);
            });
        
        // 获取地域分布数据
        fetch(`/api/location_distribution?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 更新地域分布图表
                updateMapChart(mapChart, data);
            })
            .catch(error => {
                console.error('获取地域分布数据失败:', error);
            });
        
        // 获取媒体来源分布数据
        fetch(`/api/source_distribution?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 更新媒体来源分布图表
                updateSourceChart(sourceChart, data);
            })
            .catch(error => {
                console.error('获取媒体来源分布数据失败:', error);
            });
        
        // 获取热点话题数据
        fetch(`/api/hot_topics?days=${days}`)
            .then(response => response.json())
            .then(data => {
                // 更新热点话题列表
                updateHotTopics(data);
            })
            .catch(error => {
                console.error('获取热点话题数据失败:', error);
            });
    }
    
    // 更新数据概览
    function updateOverview(data) {
        document.getElementById('totalArticles').textContent = data.total_articles || 0;
        document.getElementById('positiveCount').textContent = data.positive_count || 0;
        document.getElementById('negativeCount').textContent = data.negative_count || 0;
        document.getElementById('neutralCount').textContent = data.neutral_count || 0;
        
        if (data.top_keywords && data.top_keywords.length > 0) {
            document.getElementById('topKeywords').textContent = data.top_keywords.slice(0, 3).join(', ');
        } else {
            document.getElementById('topKeywords').textContent = '-';
        }
    }
    
    // 更新情感分布图表
    function updateSentimentChart(chart, data) {
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 10,
                data: ['正面', '负面', '中性']
            },
            series: [
                {
                    name: '情感分布',
                    type: 'pie',
                    radius: ['40%', '70%'],
                    avoidLabelOverlap: false,
                    itemStyle: {
                        borderRadius: 10,
                        borderColor: '#fff',
                        borderWidth: 2
                    },
                    label: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        label: {
                            show: true,
                            fontSize: '18',
                            fontWeight: 'bold'
                        }
                    },
                    labelLine: {
                        show: false
                    },
                    data: [
                        { value: data.positive_count || 0, name: '正面', itemStyle: { color: '#67C23A' } },
                        { value: data.negative_count || 0, name: '负面', itemStyle: { color: '#F56C6C' } },
                        { value: data.neutral_count || 0, name: '中性', itemStyle: { color: '#409EFF' } }
                    ]
                }
            ]
        };
        
        chart.setOption(option);
    }
    
    // 更新声量趋势图表
    function updateVolumeChart(chart, data) {
        const option = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['新闻文章', '社交媒体', '总计'],
                bottom: 10
            },
            grid: {
                left: '3%',
                right: '4%',
                bottom: '15%',
                top: '3%',
                containLabel: true
            },
            xAxis: {
                type: 'category',
                data: data.intervals || [],
                axisLabel: {
                    rotate: 45
                }
            },
            yAxis: {
                type: 'value'
            },
            series: [
                {
                    name: '新闻文章',
                    type: 'bar',
                    stack: 'total',
                    emphasis: {
                        focus: 'series'
                    },
                    data: data.article_counts || []
                },
                {
                    name: '社交媒体',
                    type: 'bar',
                    stack: 'total',
                    emphasis: {
                        focus: 'series'
                    },
                    data: data.social_post_counts || []
                },
                {
                    name: '总计',
                    type: 'line',
                    emphasis: {
                        focus: 'series'
                    },
                    data: data.total_counts || []
                }
            ]
        };
        
        chart.setOption(option);
    }
    
    // 更新地域分布图表
    function updateMapChart(chart, data) {
        if (data.map_config) {
            const option = JSON.parse(data.map_config);
            chart.setOption(option);
        } else {
            // 默认配置
            const option = {
                title: {
                    text: '舆情地域分布',
                    subtext: '暂无数据',
                    left: 'center'
                },
                tooltip: {
                    trigger: 'item'
                },
                visualMap: {
                    min: 0,
                    max: 10,
                    text: ['高', '低'],
                    calculable: true
                },
                series: [{
                    name: '舆情数量',
                    type: 'map',
                    map: 'china',
                    roam: true,
                    label: {
                        show: true
                    },
                    data: []
                }]
            };
            chart.setOption(option);
        }
    }
    
    // 更新媒体来源分布图表
    function updateSourceChart(chart, data) {
        // 准备数据
        const newsSourceNames = Object.keys(data.news_sources || {});
        const newsSourceValues = Object.values(data.news_sources || {});
        
        const option = {
            tooltip: {
                trigger: 'item',
                formatter: '{a} <br/>{b}: {c} ({d}%)'
            },
            legend: {
                orient: 'horizontal',
                bottom: 10,
                data: newsSourceNames
            },
            series: [
                {
                    name: '媒体来源',
                    type: 'pie',
                    radius: '70%',
                    center: ['50%', '45%'],
                    data: newsSourceNames.map((name, index) => {
                        return {
                            name: name,
                            value: newsSourceValues[index]
                        };
                    }),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };
        
        chart.setOption(option);
    }
    
    // 更新热点话题列表
    function updateHotTopics(data) {
        const hotTopicsContainer = document.getElementById('hotTopics');
        hotTopicsContainer.innerHTML = '';
        
        if (data.topics && data.topics.length > 0) {
            data.topics.forEach(topic => {
                const topicElement = document.createElement('a');
                topicElement.href = '#';
                topicElement.className = 'list-group-item list-group-item-action';
                
                // 根据情感设置不同的样式
                let sentimentClass = '';
                if (topic.sentiment_distribution) {
                    const positive = topic.sentiment_distribution.正面 || 0;
                    const negative = topic.sentiment_distribution.负面 || 0;
                    
                    if (positive > negative) {
                        sentimentClass = 'border-success';
                    } else if (negative > positive) {
                        sentimentClass = 'border-danger';
                    }
                }
                
                topicElement.classList.add(sentimentClass);
                
                topicElement.innerHTML = `
                    <div class="d-flex w-100 justify-content-between">
                        <h6 class="mb-1">${topic.keyword}</h6>
                        <small>${topic.count} 篇文章</small>
                    </div>
                    <p class="mb-1">相关文章: ${topic.articles ? topic.articles.length : 0}</p>
                `;
                
                hotTopicsContainer.appendChild(topicElement);
            });
        } else {
            hotTopicsContainer.innerHTML = '<div class="text-center p-3">暂无热点话题</div>';
        }
    }
    
    // 显示加载状态
    function showLoading() {
        // 可以添加加载动画
        document.body.style.cursor = 'wait';
    }
    
    // 隐藏加载状态
    function hideLoading() {
        document.body.style.cursor = 'default';
    }

    // 报告生成功能
    const reportTypeSelect = document.getElementById('reportType');
    const customDateRange = document.getElementById('customDateRange');
    const startDateInput = document.getElementById('startDate');
    const endDateInput = document.getElementById('endDate');
    const reportFormatSelect = document.getElementById('reportFormat');
    const generateReportBtn = document.getElementById('generateReportBtn');
    
    // 设置默认日期
    const today = new Date();
    const lastMonth = new Date();
    lastMonth.setMonth(today.getMonth() - 1);
    
    startDateInput.valueAsDate = lastMonth;
    endDateInput.valueAsDate = today;
    
    // 报告类型变化时显示/隐藏自定义日期范围
    reportTypeSelect.addEventListener('change', function() {
        if (this.value === 'custom') {
            customDateRange.style.display = 'block';
        } else {
            customDateRange.style.display = 'none';
        }
    });
    
    // 生成报告按钮点击事件
    generateReportBtn.addEventListener('click', function() {
        const reportType = reportTypeSelect.value;
        const reportFormat = reportFormatSelect.value;
        
        // 显示加载状态
        showLoading();
        
        if (reportType === 'custom') {
            // 自定义报告需要POST请求
            const startDate = startDateInput.value;
            const endDate = endDateInput.value;
            
            if (!startDate || !endDate) {
                alert('请选择开始日期和结束日期');
                hideLoading();
                return;
            }
            
            // 检查日期范围
            if (new Date(startDate) > new Date(endDate)) {
                alert('开始日期不能晚于结束日期');
                hideLoading();
                return;
            }
            
            // 发送POST请求
            fetch('/api/reports/custom', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    start_date: startDate,
                    end_date: endDate,
                    format: reportFormat
                })
            })
            .then(response => {
                hideLoading();
                
                if (reportFormat === 'json') {
                    return response.json().then(data => {
                        // 显示JSON数据
                        const jsonStr = JSON.stringify(data, null, 2);
                        const blob = new Blob([jsonStr], { type: 'application/json' });
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `自定义舆情分析报告_${startDate}至${endDate}.json`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    });
                } else {
                    // 处理二进制响应（HTML或PDF）
                    return response.blob().then(blob => {
                        const url = URL.createObjectURL(blob);
                        const a = document.createElement('a');
                        a.href = url;
                        a.download = `自定义舆情分析报告_${startDate}至${endDate}.${reportFormat}`;
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    });
                }
            })
            .catch(error => {
                hideLoading();
                console.error('生成报告失败:', error);
                alert('生成报告失败，请查看控制台获取详细信息');
            });
        } else {
            // 其他类型报告使用GET请求
            let url = `/api/reports/${reportType}?format=${reportFormat}`;
            
            if (reportType === 'daily') {
                // 每日报告可以指定天数
                const days = timeRangeSelect.value;
                url += `&days=${days}`;
            }
            
            if (reportFormat === 'json') {
                // JSON格式直接获取数据
                fetch(url)
                .then(response => response.json())
                .then(data => {
                    hideLoading();
                    
                    // 显示JSON数据
                    const jsonStr = JSON.stringify(data, null, 2);
                    const blob = new Blob([jsonStr], { type: 'application/json' });
                    const downloadUrl = URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = downloadUrl;
                    
                    let fileName = '';
                    if (reportType === 'daily') {
                        fileName = `每日舆情分析报告_${formatDate(new Date())}.json`;
                    } else if (reportType === 'weekly') {
                        fileName = `每周舆情分析报告_${formatDate(new Date())}.json`;
                    } else {
                        fileName = `每月舆情分析报告_${formatDate(new Date())}.json`;
                    }
                    
                    a.download = fileName;
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                })
                .catch(error => {
                    hideLoading();
                    console.error('生成报告失败:', error);
                    alert('生成报告失败，请查看控制台获取详细信息');
                });
            } else {
                // HTML或PDF格式直接下载文件
                hideLoading();
                window.location.href = url;
            }
        }
    });
    
    // 格式化日期为YYYYMMDD
    function formatDate(date) {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        return `${year}${month}${day}`;
    }
}); 